package context.util;

import context.com.baidu.ueditor.define.FileType;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class FileUtil {
    public static String saveImage(MultipartFile upfile) {
        String basePath = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/");
        System.out.println("当前应用上下文目录：" + basePath);

        String filename = upfile.getOriginalFilename();
        System.out.println("原始文件名：" + filename);

        String staticResDir = basePath + File.separator + "staticresource";
        String staticImgResDir = staticResDir + File.separator + "image";

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date date = new Date(System.currentTimeMillis());
        String d = dateFormat.format(date);
        System.out.println("日期：" + d);

        staticImgResDir += File.separator + d;
        System.out.println(staticImgResDir);

        File file = new File(staticImgResDir);
        if (!file.exists()) {
            file.mkdirs();
        }

        try {
            upfile.transferTo(new File(staticImgResDir, filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = "staticresource" + "/" + "image" + "/" + d + "/" + filename;
        return url;
    }

    public static String saveVideo(MultipartFile upfile) {
        String basePath = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/");

        String filename = upfile.getOriginalFilename();

        String staticResDir = basePath + File.separator + "staticresource";
        String staticImgResDir = staticResDir + File.separator + "video";

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date date = new Date(System.currentTimeMillis());
        String d = dateFormat.format(date);
        System.out.println("日期：" + d);

        staticImgResDir += File.separator + d;
        System.out.println(staticImgResDir);

        File file = new File(staticImgResDir);
        if (!file.exists()) {
            file.mkdirs();
        }

        try {
            upfile.transferTo(new File(staticImgResDir, filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = "staticresource" + "/" + "video" + "/" + d + "/" + filename;
        return url;
    }
}
